// created by noellynch
// Apr 19, 2011

package com.jsonscenegraph;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class JSONSGTransformer {
	public	String		toJSON(JSONSGNode cl_node) {
		Gson		lcl_gson = new GsonBuilder().setPrettyPrinting().create();
		return lcl_gson.toJson(cl_node);
	}
	
	public	void		toJSON(JSONSGNode cl_node, FileWriter cl_fw) {
		Gson		lcl_gson = new GsonBuilder().create();
		lcl_gson.toJson(cl_node, cl_fw);
	}
	
	public	JSONSGSpatial	fromJSON(FileReader cl_in) {
		GsonBuilder		lcl_builder = new GsonBuilder();
		lcl_builder.registerTypeAdapter(JSONSGSpatial.class, new JSONSGDeserialiser());
		
		Gson				lcl_gson = lcl_builder.create();
		
		System.out.println("JSONSGTransformer : attempting object rebuild");
		JSONSGSpatial		lcl_spatial = lcl_gson.fromJson(new BufferedReader(cl_in), JSONSGSpatial.class);
		
		System.out.println("JSONSGTransformer : rebuilt object");
		
		return lcl_spatial;
	}
	
	private	class	JSONSGDeserialiser implements JsonDeserializer<JSONSGSpatial> {
		@Override
		public JSONSGSpatial deserialize(JsonElement cl_json, Type cl_type, JsonDeserializationContext cl_context) throws JsonParseException {
//			System.out.println("json class " + cl_json.getClass());
//			System.out.println("json data\n" + cl_json);
			
			JsonObject		lcl_obj = (JsonObject)cl_json;
			String			lstr_type = lcl_obj.get("type").getAsString();
			
			if(lstr_type.equals(com.jsonscenegraph.JSONSGSpatial.Type.node.name())) {
				System.out.println("JSONSGDeserialiser : creating node");
				return cl_context.deserialize(lcl_obj, JSONSGNode.class);
			} else if(lstr_type.equals(com.jsonscenegraph.JSONSGSpatial.Type.mesh.name())){
				System.out.println("JSONSGDeserialiser : creating mesh");
				return cl_context.deserialize(lcl_obj, JSONSGMesh.class);
			}
			
			return null;
		}
		
	}
}
